#include "ipcuty.h"

char g_sem_path[] = "/usr";
int  g_sem_item   = 123;

///////////////////////////////////////////////////////////////////////////////
////////////// sem functions


int	sem_create_u()
{
	return sem_create(g_sem_path, g_sem_item);
}
int	sem_get_u()
{
	return sem_get(g_sem_path, g_sem_item);
}

int sem_create(char filepath[], int itemid)	
{
	key_t 		semkey;
	int			semid;
	union semun su;

	if((semkey = ftok(filepath, itemid)) == -1){
		return -1;
	}
	if((semid = semget(semkey, 1, IPC_CREAT | 0666)) == -1){
		return -1;
	}
	
	su.val = 1;
	semctl(semid, 0, SETVAL, su);
//	semctl(semid, 1, SETVAL, su);

	return semid;
}

int sem_get(char filepath[], int itemid)
{
	key_t 	semkey;
	int 	semid;
	if((semkey = ftok(filepath, itemid)) == -1){
		return -1;
	}
	if((semid = semget(semkey, 0, 0)) == -1){
		return -1;
	}
	return semid;
}

int sem_p(int semid)
{
	struct sembuf sb;
	sb.sem_num 	= 0;
	sb.sem_op	= -1;
	sb.sem_flg	= 0;
	return (semop(semid, &sb, 1));
}
/*
int sem_p2(int semid)
{
	struct sembuf sb;
	sb.sem_num 	= 1;
	sb.sem_op	= -1;
	sb.sem_flg	= 0;
	return (semop(semid, &sb, 1));
}
*/
int sem_v(int semid)
{
	struct sembuf sb;
	sb.sem_num	= 0;
	sb.sem_op	= 1;
	sb.sem_flg	= 0;
	return (semop(semid, &sb, 1));
}
/*
int sem_v2(int semid)
{
	struct sembuf sb;
	sb.sem_num	= 1;
	sb.sem_op	= 1;
	sb.sem_flg	= 0;
	return (semop(semid, &sb, 1));
}
*/
int sem_destroy(int semid)
{
	int ret;
	union semun su;
	su.val = 0;
	return semctl(semid, 0, IPC_RMID, su);
}

/////////////////////////////////////////////////////////////////////////////
/////////////////// shm functions
/*
int shm_create(char filepath[], int itemid, size_t size)
{
	key_t 	shmkey;
	int		shmid;
	
	if((shmkey = ftok(filepath, itemid)) == -1){
		return -1;
	}
	if((shmid = shmget(shmkey, size, IPC_CREAT | 0666)) == -1){
		return -1;
	}

	return shmid;
}

int	shm_get(char filepath[], int itemid)
{
	key_t	shmkey;
	int		shmid;

	if((shmkey = ftok(filepath, itemid)) == -1){
		return -1;
	}
	if((shmid = shmget(shmkey, 0, 0)) == -1){
		return -1;
	}

	return shmid;
}

int shm_destroy(int shmid)
{
//	int ret;
//	ret = shmctl(shmid, IPC_RMID, NULL);
//	return (-1 != ret);	
	return shmctl(shmid, IPC_RMID, NULL);
}
*/
